<?php
/**
 * 菜单服务
 * @Auther 聂哥<376927050@qq.com>
 * @Date: 2022-10-12 11:27:48
*/
namespace app\admin\model\system;

use think\facade\Cookie;
use think\facade\Session;

class SystemUser extends BaseModel
{
    public $error;
    
    /**
     * 判断是否登录
     * @return bool|array
     */
    public function isLogin()
    {
        return session('admin');
    }

    /**
     * 用户登录验证
     */
    public function login($username = '', $password = '')
    {
        //验证账户密码
        $admin = self::where('username',$username)->find();
        if (!$admin) {
            $this->error = '用户不存在';
            return false;
        }
        if( $admin->status == self::DISABLED_STATE ){
            $this->error = '用户已经被禁用';
            return false;
        }
        if( password_verify($password,$admin->password) == false ){
            $this->error = '输入的密码错误';
            return false;
        }
       
        // 用户信息存入会话
        session('admin', [
            'id' => $admin->id,
            'role_ids' => $admin->role_ids,
            'username' => $admin->username,
            'nickname' => $admin->nickname,
            'headimgurl' => $admin->headimgurl
        ]);
        return true;
    }

     /**
     * 退出登陆
     * @return bool
     */
    public function logout()
    {
        Session::delete('admin');
        Cookie::delete('hash');
        return true;
    }

    /**
     * 定义获取器 获取用户所在组
     */
    public function getRoleIdsAttr($value,$data)
   {
        $userModel = self::with('roles')->find($data['id'])->toArray();
        if( $userModel != null ){
            return array_column($userModel['roles'],'id');
        }
   }
    
    /**
     * 管理拥有的角色
     */
    public function roles()
    {
        return $this->belongsToMany(SystemRole::class, SystemUserRole::class, 'role_id','user_id');
    }

    public function hasRoles()
    {
        return $this->hasMany(SystemUserRole::class,'user_id','id');
    }

}